/**
 * 
 */
package com.massyframework.beanskin.launcher.scanning.maven;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Objects;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * {@link MavenSettings}, maven设置
 * @author huangkh
 *
 */
class MavenSettings {

	private static final String M2_HOME    = "M2_HOME";
	private static final String MAVEN_HOME = "MAVEN_HOME";

    private static MavenSettings INSTANCE = new MavenSettings();

    private Path localRepository = null;

    MavenSettings() {
    	this.localRepository = 
    			this.checkExistAndIsDirectory(
    					this.parseLocalRepositoryDirectory(), "\"localRepository\" ");
    }

    public static MavenSettings getInstance()  {
        return INSTANCE;
    }
    
    /**
     * 解析maven的配置文件，定位maven本地仓储目录的位置
     * @param home
     * @return
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    protected String parseLocalRepositoryDirectory() {
    	String result = null;
    	String home = this.getHome();
    	if (home != null) {
	        File settings =  new File(home, "conf/settings.xml");
	        if (settings != null) {
	        	try {
		        	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		            DocumentBuilder builder = factory.newDocumentBuilder();
		            Document doc = builder.parse(settings);
		            NodeList list = doc.getElementsByTagName("localRepository");
		            if (list.getLength()>0){
		                result = list.item(0).getTextContent();
		            }		          
	        	}catch(Exception e) {
	        		
	        	}
	        }

    	}

        if (result == null) {
        	//返回缺省的目录
        	result = System.getProperty("user.home").concat(File.separator)
        			.concat(".m2").concat(File.separator).concat("repository");
        }
        
        return result;
    }

    /**
     * 检查home不能为null,且目录存在
     * @param file {@link File}
     * @return {@link Path}
     */
    protected Path checkExistAndIsDirectory(String file, String message){
        Objects.requireNonNull(file, message);

        File result = new File(file);
        if (!result.exists()){
            throw new RuntimeException(file + " isnot exists.");
        }
        if (!result.isDirectory()){
            throw new RuntimeException(file + " isnot be directory.");
        }
        return result.toPath();
    }

    /**
     * 从环境变量中获取M2_HOME
     * @return {@link String}
     */
    private String getHome(){
        String result = System.getProperty(M2_HOME, System.getenv(M2_HOME));
                
        if (result == null) {
        	result = System.getProperty(MAVEN_HOME, System.getenv(MAVEN_HOME));
        }
        
        return result;
    }

    public void setLocalRepository(Path localRepository) {
        this.localRepository = localRepository;
    }

    public Path getLocalRepository() {
        return localRepository;
    }    
}
